package com.billdowney.util.encrypt;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Hex;

public class HmacUtil {

	public static String strToHmacByMD5(String str) {
		KeyGenerator keyGenerator = null;
		Mac mac = null;
		try {
			// 初始化KeyGenerator
			keyGenerator = KeyGenerator.getInstance("HmacMD5");
			// 产生秘钥
			SecretKey secretKey = keyGenerator.generateKey();
			// 获得秘钥
			byte[] key = secretKey.getEncoded();
			// 还原秘钥
			SecretKey restoreSecretKey = new SecretKeySpec(key, "HmacMD5");
			// 实例化MAC
			mac = Mac.getInstance(restoreSecretKey.getAlgorithm());
			// 初始化MAC
			mac.init(restoreSecretKey);
			mac.doFinal(str.getBytes());
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		return Hex.encodeHexString(mac.doFinal(str.getBytes()));
	}

}
